extends Node

## 怪物管理器
## 负责管理游戏中的所有怪物数据，包括加载、查询和管理怪物信息

signal monsters_loaded(count: int)
signal monster_data_error(message: String)

# 怪物数据存储
var monsters_database: Dictionary = {}
var monsters_by_level: Dictionary = {}
var monsters_by_rarity: Dictionary = {}
var monsters_by_scene: Dictionary = {}  # 按场景索引怪物
var monsters_data_path: String = "res://data/monsters/monsters.json"

# 稀有度权重配置
var rarity_weights: Dictionary = {
	"common": 60,
	"uncommon": 30,
	"rare": 8,
	"epic": 2,
	"legendary": 0.5
}

func _ready():
	"""初始化怪物管理器"""
	process_mode = Node.PROCESS_MODE_ALWAYS
	load_monsters_data()

func load_monsters_data():
	"""从JSON文件加载怪物数据"""
	if not FileAccess.file_exists(monsters_data_path):
		var error_msg = "怪物数据文件不存在: " + monsters_data_path
		print("错误：" + error_msg)
		monster_data_error.emit(error_msg)
		return
	
	var file = FileAccess.open(monsters_data_path, FileAccess.READ)
	if file == null:
		var error_msg = "无法打开怪物数据文件: " + monsters_data_path
		print("错误：" + error_msg)
		monster_data_error.emit(error_msg)
		return
	
	var json_string = file.get_as_text()
	file.close()
	
	var json = JSON.new()
	var parse_result = json.parse(json_string)
	if parse_result != OK:
		var error_msg = "解析怪物数据JSON失败: " + json.get_error_message()
		print("错误：" + error_msg)
		monster_data_error.emit(error_msg)
		return
	
	var data = json.data
	if not data.has("monsters"):
		var error_msg = "怪物数据文件格式错误，缺少monsters字段"
		print("错误：" + error_msg)
		monster_data_error.emit(error_msg)
		return
	
	# 清空现有数据
	clear_all_data()
	
	# 加载怪物数据并建立索引
	var loaded_count = 0
	for monster_data in data["monsters"]:
		if validate_monster_data(monster_data):
			store_monster_data(monster_data)
			loaded_count += 1
		else:
			print("警告：跳过无效的怪物数据: ", monster_data)
	
	print("成功加载 %d 个怪物数据" % loaded_count)
	monsters_loaded.emit(loaded_count)

func validate_monster_data(monster_data: Dictionary) -> bool:
	"""验证怪物数据的完整性"""
	var required_fields = ["id", "name", "max_hp", "attack", "defense", "sprite_path"]
	for field in required_fields:
		if not monster_data.has(field):
			print("错误：怪物数据缺少必需字段: ", field)
			return false
	
	# 检查数值字段的有效性
	if monster_data["max_hp"] <= 0 or monster_data["attack"] < 0 or monster_data["defense"] < 0:
		print("错误：怪物数据包含无效的数值")
		return false
	
	return true

func store_monster_data(monster_data: Dictionary):
	"""存储怪物数据并建立索引"""
	var monster_id = monster_data["id"]
	
	# 存储到主数据库
	monsters_database[monster_id] = monster_data
	
	# 按等级索引
	if monster_data.has("level"):
		var level = monster_data["level"]
		if not monsters_by_level.has(level):
			monsters_by_level[level] = []
		monsters_by_level[level].append(monster_id)
	
	# 按稀有度索引
	if monster_data.has("rarity"):
		var rarity = monster_data["rarity"]
		if not monsters_by_rarity.has(rarity):
			monsters_by_rarity[rarity] = []
		monsters_by_rarity[rarity].append(monster_id)
	
	# 按场景索引
	if monster_data.has("spawn_areas"):
		var spawn_areas = monster_data["spawn_areas"]
		for scene_key in spawn_areas:
			if not monsters_by_scene.has(scene_key):
				monsters_by_scene[scene_key] = []
			monsters_by_scene[scene_key].append(monster_id)

func clear_all_data():
	"""清空所有数据"""
	monsters_database.clear()
	monsters_by_level.clear()
	monsters_by_rarity.clear()
	monsters_by_scene.clear()

func get_monster_by_id(monster_id: String) -> Dictionary:
	"""根据ID获取怪物数据"""
	if monsters_database.has(monster_id):
		var monster_data = monsters_database[monster_id].duplicate()
		# 设置当前生命值等于最大生命值
		monster_data["current_hp"] = monster_data["max_hp"]
		return monster_data
	return {}

func get_monsters_by_level(level: int) -> Array[Dictionary]:
	"""获取指定等级的怪物"""
	var result: Array[Dictionary] = []
	if monsters_by_level.has(level):
		for monster_id in monsters_by_level[level]:
			result.append(get_monster_by_id(monster_id))
	return result

func get_monsters_by_level_range(min_level: int, max_level: int) -> Array[Dictionary]:
	"""获取指定等级范围内的怪物"""
	var result: Array[Dictionary] = []
	for level in range(min_level, max_level + 1):
		result.append_array(get_monsters_by_level(level))
	return result

func get_monsters_by_rarity(rarity: String) -> Array[Dictionary]:
	"""根据稀有度获取怪物"""
	var result: Array[Dictionary] = []
	if monsters_by_rarity.has(rarity):
		for monster_id in monsters_by_rarity[rarity]:
			result.append(get_monster_by_id(monster_id))
	return result

func get_random_monster() -> Dictionary:
	"""获取随机怪物"""
	if monsters_database.is_empty():
		return {}
	
	var monster_ids = monsters_database.keys()
	var random_id = monster_ids[randi() % monster_ids.size()]
	return get_monster_by_id(random_id)

func get_random_monster_by_rarity_weight() -> Dictionary:
	"""根据稀有度权重获取随机怪物"""
	if monsters_database.is_empty():
		return {}
	
	# 计算总权重
	var total_weight = 0.0
	for rarity in rarity_weights.keys():
		if monsters_by_rarity.has(rarity) and not monsters_by_rarity[rarity].is_empty():
			total_weight += rarity_weights[rarity]
	
	if total_weight <= 0:
		return get_random_monster()
	
	# 随机选择稀有度
	var random_value = randf() * total_weight
	var current_weight = 0.0
	
	for rarity in rarity_weights.keys():
		if monsters_by_rarity.has(rarity) and not monsters_by_rarity[rarity].is_empty():
			current_weight += rarity_weights[rarity]
			if random_value <= current_weight:
				# 从该稀有度中随机选择一个怪物
				var monsters_of_rarity = monsters_by_rarity[rarity]
				var random_id = monsters_of_rarity[randi() % monsters_of_rarity.size()]
				return get_monster_by_id(random_id)
	
	return get_random_monster()

func get_random_monster_by_level_range(min_level: int, max_level: int) -> Dictionary:
	"""获取指定等级范围内的随机怪物"""
	var available_monsters = get_monsters_by_level_range(min_level, max_level)
	if available_monsters.is_empty():
		return {}
	
	return available_monsters[randi() % available_monsters.size()]

func get_monsters_by_scene(scene_key: String) -> Array[Dictionary]:
	"""根据场景key获取怪物列表"""
	var result: Array[Dictionary] = []
	if monsters_by_scene.has(scene_key):
		for monster_id in monsters_by_scene[scene_key]:
			result.append(get_monster_by_id(monster_id))
	return result

func get_random_monster_by_scene(scene_key: String) -> Dictionary:
	"""根据场景key获取随机怪物"""
	if not monsters_by_scene.has(scene_key) or monsters_by_scene[scene_key].is_empty():
		print("警告：场景 %s 中没有配置怪物，使用默认随机怪物" % scene_key)
		return get_random_monster_by_rarity_weight()
	
	# 从该场景的怪物中随机选择一个
	var scene_monsters = monsters_by_scene[scene_key]
	var random_id = scene_monsters[randi() % scene_monsters.size()]
	return get_monster_by_id(random_id)

func get_random_monster_by_scene_with_rarity_weight(scene_key: String) -> Dictionary:
	"""根据场景key和稀有度权重获取随机怪物"""
	if not monsters_by_scene.has(scene_key) or monsters_by_scene[scene_key].is_empty():
		print("警告：场景 %s 中没有配置怪物，使用默认随机怪物" % scene_key)
		return get_random_monster_by_rarity_weight()
	
	# 获取该场景中的怪物，按稀有度分组
	var scene_monsters_by_rarity: Dictionary = {}
	for monster_id in monsters_by_scene[scene_key]:
		var monster_data = monsters_database[monster_id]
		var rarity = monster_data.get("rarity", "common")
		if not scene_monsters_by_rarity.has(rarity):
			scene_monsters_by_rarity[rarity] = []
		scene_monsters_by_rarity[rarity].append(monster_id)
	
	# 计算该场景中可用稀有度的总权重
	var total_weight = 0.0
	for rarity in scene_monsters_by_rarity.keys():
		if rarity_weights.has(rarity):
			total_weight += rarity_weights[rarity]
	
	if total_weight <= 0:
		# 如果没有权重配置，直接随机选择
		return get_random_monster_by_scene(scene_key)
	
	# 根据权重随机选择稀有度
	var random_value = randf() * total_weight
	var current_weight = 0.0
	
	for rarity in scene_monsters_by_rarity.keys():
		if rarity_weights.has(rarity):
			current_weight += rarity_weights[rarity]
			if random_value <= current_weight:
				# 从该稀有度的怪物中随机选择
				var monsters_of_rarity = scene_monsters_by_rarity[rarity]
				var random_id = monsters_of_rarity[randi() % monsters_of_rarity.size()]
				return get_monster_by_id(random_id)
	
	# 备用方案
	return get_random_monster_by_scene(scene_key)

func get_all_monsters() -> Array[Dictionary]:
	"""获取所有怪物数据"""
	var result: Array[Dictionary] = []
	for monster_id in monsters_database.keys():
		result.append(get_monster_by_id(monster_id))
	return result

func get_monster_count() -> int:
	"""获取怪物总数"""
	return monsters_database.size()

func has_monster(monster_id: String) -> bool:
	"""检查是否存在指定ID的怪物"""
	return monsters_database.has(monster_id)

func get_available_levels() -> Array[int]:
	"""获取所有可用的怪物等级"""
	var levels: Array[int] = []
	for level in monsters_by_level.keys():
		levels.append(level)
	levels.sort()
	return levels

func get_available_rarities() -> Array[String]:
	"""获取所有可用的稀有度"""
	var rarities: Array[String] = []
	for rarity in monsters_by_rarity.keys():
		rarities.append(rarity)
	return rarities

func reload_monsters_data():
	"""重新加载怪物数据"""
	load_monsters_data()

func set_rarity_weight(rarity: String, weight: float):
	"""设置稀有度权重"""
	rarity_weights[rarity] = max(0.0, weight)

func get_rarity_weight(rarity: String) -> float:
	"""获取稀有度权重"""
	return rarity_weights.get(rarity, 0.0)

func calculate_monster_drops(monster_id: String) -> Array[Dictionary]:
	"""计算怪物掉落物品"""
	var drops: Array[Dictionary] = []
	
	if not monsters_database.has(monster_id):
		print("警告：未找到怪物ID: ", monster_id)
		return drops
	
	var monster_data = monsters_database[monster_id]
	
	# 计算金币掉落（所有怪物都会掉落金币）
	_calculate_gold_drop(monster_data, drops)
	
	if not monster_data.has("drops"):
		# 即使没有配置掉落，也检查幻兽幼崽掉落
		_check_phantom_beast_cub_drop(monster_id, drops)
		return drops
	
	var drop_config = monster_data["drops"]
	
	# 处理装备掉落
	if drop_config.has("equipment"):
		for equipment_drop in drop_config["equipment"]:
			if _roll_drop_chance(equipment_drop["chance"]):
				drops.append({
					"type": "equipment",
					"id": equipment_drop["id"],
					"quantity": 1
				})
	
	# 处理消耗品掉落
	if drop_config.has("consumables"):
		for consumable_drop in drop_config["consumables"]:
			if _roll_drop_chance(consumable_drop["chance"]):
				var quantity = _calculate_consumable_quantity(consumable_drop)
				drops.append({
					"type": "consumable",
					"id": consumable_drop["id"],
					"quantity": quantity
				})
	
	# 处理材料掉落
	if drop_config.has("materials"):
		for material_drop in drop_config["materials"]:
			if _roll_drop_chance(material_drop["chance"]):
				var quantity = _calculate_material_quantity(material_drop)
				drops.append({
					"type": "material",
					"id": material_drop["id"],
					"quantity": quantity
				})
	
	# 检查幻兽幼崽掉落（所有怪物都有机会掉落）
	_check_phantom_beast_cub_drop(monster_id, drops)
	
	return drops

func _roll_drop_chance(chance: float) -> bool:
	"""根据概率判断是否掉落"""
	return randf() * 100.0 <= chance

func _calculate_consumable_quantity(_drop_config: Dictionary) -> int:
	"""计算消耗品掉落数量"""
	# 基础数量为1，有小概率掉落更多
	var base_quantity = 1
	var bonus_chance = randf() * 100.0
	
	if bonus_chance <= 5.0:  # 5%概率掉落3个
		return base_quantity + 2
	elif bonus_chance <= 15.0:  # 10%概率掉落2个
		return base_quantity + 1
	else:
		return base_quantity

func _calculate_material_quantity(_drop_config: Dictionary) -> int:
	"""计算材料掉落数量"""
	# 材料可以掉落更多数量
	var base_quantity = 1
	var bonus_chance = randf() * 100.0
	
	if bonus_chance <= 2.0:  # 2%概率掉落5个
		return base_quantity + 4
	elif bonus_chance <= 8.0:  # 6%概率掉落4个
		return base_quantity + 3
	elif bonus_chance <= 20.0:  # 12%概率掉落3个
		return base_quantity + 2
	elif bonus_chance <= 40.0:  # 20%概率掉落2个
		return base_quantity + 1
	else:
		return base_quantity

func get_drops_by_monster_level(monster_level: int) -> Dictionary:
	"""获取指定等级怪物可能掉落的所有物品类型统计"""
	var level_drops = {
		"equipment": [],
		"consumables": [],
		"materials": []
	}
	
	for monster_id in monsters_database.keys():
		var monster_data = monsters_database[monster_id]
		if monster_data.get("level", 0) == monster_level and monster_data.has("drops"):
			var drops = monster_data["drops"]
			
			for category in ["equipment", "consumables", "materials"]:
				if drops.has(category):
					for item in drops[category]:
						if not level_drops[category].has(item["id"]):
							level_drops[category].append(item["id"])
	
	return level_drops

func get_monster_drop_info(monster_id: String) -> Dictionary:
	"""获取怪物掉落信息"""
	if not monsters_database.has(monster_id):
		return {}
	
	var monster_data = monsters_database[monster_id]
	return monster_data.get("drops", {})

func _calculate_gold_drop(monster_data: Dictionary, drops: Array[Dictionary]):
	"""计算金币掉落"""
	if not monster_data.has("gold_drop"):
		# 如果没有配置金币掉落，使用默认值
		var default_gold = _get_default_gold_by_level(monster_data.get("level", 1))
		drops.append({
			"type": "gold",
			"id": "gold",
			"quantity": default_gold
		})
		return
	
	var gold_config = monster_data["gold_drop"]
	var min_gold = gold_config.get("min", 1)
	var max_gold = gold_config.get("max", 3)
	
	# 在最小值和最大值之间随机生成金币数量
	var gold_amount = randi_range(min_gold, max_gold)
	
	drops.append({
		"type": "gold",
		"id": "gold",
		"quantity": gold_amount
	})

func _get_default_gold_by_level(level: int) -> int:
	"""根据怪物等级获取默认金币掉落数量"""
	if level <= 5:
		return randi_range(1, 3)
	elif level <= 10:
		return randi_range(3, 8)
	elif level <= 15:
		return randi_range(8, 15)
	elif level <= 20:
		return randi_range(15, 25)
	else:
		return randi_range(25, 50)

func _check_phantom_beast_cub_drop(monster_id: String, drops: Array[Dictionary]):
	"""检查幻兽幼崽掉落"""
	if not PhantomBeastManager:
		return
	
	# 基础掉落概率：5%
	var base_drop_chance = 5.0
	
	# 根据怪物稀有度调整掉落概率
	var monster_data = monsters_database.get(monster_id, {})
	var rarity = monster_data.get("rarity", "common")
	
	var drop_chance = base_drop_chance
	match rarity:
		"common":
			drop_chance = 5.0  # 5%
		"uncommon":
			drop_chance = 8.0  # 8%
		"rare":
			drop_chance = 12.0  # 12%
		"epic":
			drop_chance = 18.0  # 18%
		"legendary":
			drop_chance = 25.0  # 25%
	
	# 掉落检定
	if _roll_drop_chance(drop_chance):
		# 成功掉落幻兽幼崽
		drops.append({
			"type": "phantom_beast",
			"id": monster_id,  # 使用怪物ID作为幻兽类型
			"quantity": 1
		})
		print("幻兽幼崽掉落成功: %s" % monster_data.get("name", monster_id))
